package org.apache.flink.runtime.rest.handler.cluster;

import java.util.Map;
import java.util.concurrent.CompletableFuture;

import org.apache.flink.api.common.time.Time;
import org.apache.flink.runtime.resourcemanager.ResourceManagerGateway;
import org.apache.flink.runtime.resourcemanager.ResourceOverview;
import org.apache.flink.runtime.rest.handler.HandlerRequest;
import org.apache.flink.runtime.rest.handler.RestHandlerException;
import org.apache.flink.runtime.rest.handler.resourcemanager.AbstractResourceManagerHandler;
import org.apache.flink.runtime.rest.legacy.messages.ClusterOverviewWithVersion;
import org.apache.flink.runtime.rest.messages.EmptyMessageParameters;
import org.apache.flink.runtime.rest.messages.EmptyRequestBody;
import org.apache.flink.runtime.rest.messages.MessageHeaders;
import org.apache.flink.runtime.rpc.retriever.GatewayRetriever;
import org.apache.flink.runtime.util.EnvironmentInformation;
import org.apache.flink.runtime.webmonitor.RestfulGateway;

/** Handler which returns the cluster overview information with version. */
public class ClusterOverviewHandler
        extends AbstractResourceManagerHandler<
                RestfulGateway,
                EmptyRequestBody,
                ClusterOverviewWithVersion,
                EmptyMessageParameters> {

    private static final String version = EnvironmentInformation.getVersion();

    private static final String commitID = EnvironmentInformation.getRevisionInformation().commitId;

    public ClusterOverviewHandler(
            GatewayRetriever<? extends RestfulGateway> leaderRetriever,
            Time timeout,
            Map<String, String> responseHeaders,
            MessageHeaders<EmptyRequestBody, ClusterOverviewWithVersion, EmptyMessageParameters> messageHeaders,
            GatewayRetriever<ResourceManagerGateway> resourceManagerGatewayRetriever) {
        super(leaderRetriever, timeout, responseHeaders, messageHeaders, resourceManagerGatewayRetriever);
    }

	@Override
	protected CompletableFuture<ClusterOverviewWithVersion> handleRequest(HandlerRequest<EmptyRequestBody> request,
			ResourceManagerGateway gateway) throws RestHandlerException {
        CompletableFuture<ResourceOverview> overviewFuture = gateway.requestResourceOverview(timeout);

        return overviewFuture.thenApply(
                resourceOverview ->
                        ClusterOverviewWithVersion.fromResourceOverview(
                                resourceOverview, version, commitID));
	}
}
